<!--订单列表模块-->
<template>
  <view class="order_item" :class="showLoaded?'hidePage':'showPage'">
    <block v-for="(item, index) in orderList" :key="index">
      <view class="list" :key="index">
        <block v-if="isRefundList == 'Y'">
          <navigator class="item_content" hover-class="none"
            :url="'/pages/return/details?refundId=' + item.refundId + '&orderNo=' + item.orderId">
            <view class="order_list_top">
              <view class="title">
                <view class="order_doc">{{ item.refundCode }}</view>
              </view>
              <view class="title">
                <view class="order_doc">{{ item.created }}</view>
              </view>
              <view>
                <view class="order_state">
                  {{ orderStatusList[item.status] }}
                </view>
              </view>
            </view>
            <view class="order_list_center">
              <productList :imageHeight.sync="imageHeight" :orderCode.sync="item.orderCode" :list.sync="item.items" :isC2b.sync="item.isC2bOrder"
                :isRefundList.sync="isRefundList" @onCustomizationDetails="onCustomizationDetails"></productList>
            </view>
          </navigator>
        </block>

        <block v-else>
          <navigator class="item_content" hover-class="none" :url="'/pages/order/details?orderNo=' + item.orderId">
            <view class="order_list_top">
              <view>
                <text class="order_text">
                  {{((item.status == "WAIT_BUYER_PAY") || (item.status == 'TRADE_CLOSED_BY_CLOUD') || (item.approveStatus == -1 && item.status == 'CLOSED') || ( item.status == 'TRADE_CLOSED') )&& !item.addition.activitySelectionRecordId && !item.addition.hasPrivateSaleSku && openAppointment ? '预约申请编号：' : '订单编号：'}}
                </text>
                <text class="order_text">
                  {{(item.status == 'WAIT_BUYER_PAY' || ( item.status == 'TRADE_CLOSED_BY_CLOUD') || ( item.status == 'TRADE_CLOSED')) && !item.addition.activitySelectionRecordId && !item.addition.hasPrivateSaleSku && openAppointment ? ("Y" + item.orderCode) : item.orderCode }}
                </text>
              </view>
              <view class="order_state"
                :style="{color: (item.status=='WAIT_BUYER_PAY' || item.status == 'BUYER_PART_PAYMENT') ? '#CB171A' : '#75777A'}">
                  {{(item.status == 'TRADE_FINISHED'&& item.orderItemsRefundStatus == 'Refunded') ? '已退款' : (item.status == "WAIT_BUYER_PAY" && item.approveStatus == 0 && openAppointment) ? '待审核' : ((item.status == "WAIT_BUYER_PAY" && item.approveStatus == -1) || (item.status == "TRADE_CLOSED_BY_CLOUD" && item.approveStatus == -1) || (item.status == "CLOSED" && item.approveStatus == -1)) && openAppointment ? '预约申请未成功' : item.status == "WAIT_BUYER_PAY" && item.approveStatus == 1 && openAppointment ? '待提交订单并付款' : (item.status == 'TRADE_FINISHED' && item.refundStatus == 'NO_REFUND') ? '已签收' : orderStatusList[item.status]}}
                  <block
                    v-if="(((item.status == 'WAIT_BUYER_PAY' || item.status == 'BUYER_PART_PAYMENT') && item.approveStatus == 1 && openAppointment) || (item.status == 'WAIT_BUYER_PAY' || item.status == 'BUYER_PART_PAYMENT') && !openAppointment) && item.cuttime > 0">
                    <text style="margin-right: 4rpx;">剩</text>
                    <block v-if="isIos">
                      <u-count-down color='#CB171A' separator-color='#CB171A' separator-size="20" bg-color="#fafafa" :colonPadding="true"
                        style="font-family: FrankNew-Regular,NotoSansSC-Regular;font-weight: 400;line-height: 32rpx;" :timestamp="item.cuttime" :show-hours="true"
                        font-size='20' @end='endCutdown(item,index)'>
                      </u-count-down>
                    </block>
										<view v-if="!isIos">
											<u-count-down color='#CB171A' separator-color='#CB171A' separator-size="20" bg-color="#fafafa" :colonPadding="true"
											  style="font-family: FrankNew-Regular,NotoSansSC-Regular;font-weight: 400;line-height: 32rpx;" :timestamp="item.cuttime" :show-hours="true"
											  font-size='20' @end='endCutdown(item,index)'>
											</u-count-down>
										</view>
                  </block>

              </view>
            </view>
            <view class="order_list_center">
              <productList :imageHeight.sync="imageHeight" :orderCode.sync="item.orderCode" :list.sync="item.items" :isC2b.sync="item.isC2bOrder"
                :isRefundList.sync="isRefundList" @onCustomizationDetails="onCustomizationDetails"></productList>
            </view>
          </navigator>
        </block>
        <view class="order_list_footer" v-if="isRefundList == 'N'">
          <view class="btn_group">
            <view class="btn btn_pay" @click="payMoney" :data-payType="item.payType" :data-id="item.orderId"
              :data-ordercode="item.orderCode" :data-index="index"
              v-if="item.status === 'WAIT_BUYER_PAY' && item.approveStatus == 1 && openAppointment">
              提交订单并付款
            </view>
            <view class="btn btn_pay" @click="payMoney" :data-payType="item.payType" :data-id="item.orderId"
              :data-ordercode="item.orderCode" :data-index="index"
              v-else-if="item.status === 'WAIT_BUYER_PAY' && !openAppointment">
              立即支付
            </view>

            <view class="btn btn_pay" @click="payMoney" :data-payType="item.payType" :data-id="item.orderId"
              :data-ordercode="item.orderCode" :data-index="index"
              v-else-if="item.status === 'BUYER_PART_PAYMENT' &&  (!openAppointment || (openAppointment && item.approveStatus == 1))">
              继续付款
            </view>
            <view class="btn btn_check" @click="orderDetail(item,index)">查看详情</view>
            <view class="btn btn_check" :data-id="item.orderId" @click="checkLogistics" v-if="(item.status == 'TRADE_FINISHED'&& item.orderItemsRefundStatus == 'Completed' || item.status == 'WAIT_BUYER_CONFIRM_GOODS') && item.shipTime != null">
              查看物流</view>
            <view class="btn btn_del" @click="cancelOrder" :data-id="item.orderId" :data-ordercode="item.orderCode"
              :data-index="index" :data-draw="item.addition.activitySelectionRecordId"
              :data-special="item.addition.hasPrivateSaleSku" :data-status="item.status"
              v-if="item.status === 'WAIT_BUYER_PAY' && item.approveStatus !== -1 && openAppointment || ((item.status == 'WAIT_BUYER_PAY' || item.status == 'BUYER_PART_PAYMENT') && !openAppointment)">
              取消订单</view>
            <block v-if="item.status == 'TRADE_FINISHED' && item.orderItemsRefundStatus == 'Completed'">
              <view class="btn btn_del" v-if="
                (item.invoiceType == 0 && applyLists.includes(item.invoiceStatus) && item.shipTime!==null && item.invoiceAmount>0) ||
                (item.invoiceType == 1 && item.invoiceStatus == 5 && item.shipTime!==null && item.invoiceAmount>0)
                " @click="applyInvoice(item.orderId)">
                <view>申请发票</view>
              </view>
              <view class="btn btn_del" v-if="lookLists.includes(item.invoiceStatus)">
                <navigator hover-class="none" :url="'/pages/invoice/list?orderNo=' + item.orderId">
                  <view>查看发票</view>
                </navigator>
              </view>
            </block>
          </view>
        </view>

        <view v-if="isRefundList == 'Y'" class="order_list_footer">
          <view class="btn_group">
            <view class="btn btn_check" :data-id="item.orderId" :data-refundId="item.refundId" @click="goToRmaDetail">
              查看详情</view>
            <view class="btn btn_check" :data-id="item.orderId" @click="checkLogistics" v-if="item.shipTime != null">
              查看物流</view>
          </view>
        </view>
      </view>
    </block>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
		<!-- 个性化定制内容查看 -->
		<c2bDetails ref="c2bDetailsPopup"></c2bDetails>
  </view>
</template>
<script module="filterChecked" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
  import tip from '@/utils/tip';
  import ProductList from '@/components/productList/productList';
	import c2bDetails from './components/c2bDetails';
  import api from '@/api/api';
  import {
    CUSTOMER_INFO,
    MERCHANT_INFO,
    USER_SPECICAL_INFO
  } from '@/utils/constant';
  export default {
    props: {
      orderList: {
        default: [],
        flag: '',
        orderNo: ''
      },
      orderStatusList: {
        default: []
      },
      isRefundList: {
        default: 'N'
      },
      showLoaded: {
        type: Boolean
      }
    },
    components: {
      productList: ProductList,
			c2bDetails: c2bDetails
    },

    data() {
      return {
        subscribeMessage: [],
        imageHeight: 180,
        touchStartTime: '',
        listIndex: 0,
        openAppointment: this.$programSetting.openAppointment,
        btnActive: true,
        currentCancelIndex: 0,
        lookLists:[2,3,5],  //  发票状态为 2,3,5 展示查看发票按钮
        applyLists:[0,1,4],  //  发票状态为 0,1,4 展示申请发票按钮
				isIos: false
      };
    },
    mounted() {
      this.imageHeight = 120 / uni.getStorageSync('imageScaling');
			
			this.isIos = wx.getSystemInfoSync().system.includes('iOS') ? true : false;
    },
    methods: {
			onCustomizationDetails(oId){
				const res = this.orderList.find(item=>item.orderId === oId);
				if(!res || !res.addition || !res.addition.customizationImg) return this.handleShowTextToast('定制信息回显异常');
				this.$refs.c2bDetailsPopup.show(res.addition);
			},
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){
				const {type,callBackData} = data;
				if(callBackData && callBackData.type){
					//	取消订单确认
					if(callBackData.type === "editOrderInfo"){
						if(type === 'confirm' && callBackData.data){
							this.editOrderInfo(callBackData.data.orderNo, callBackData.data.flag, callBackData.data.isCancelOrder)
						}else{
							this.btnActive = true
						}
					}
					//	确认收货提示弹窗
					if(type === 'confirm' && callBackData.type === "handleAjaxConfirmOrder"){
						this.handleAjaxConfirmOrder(callBackData.data);
					}
				}
				
			},
      setActive() {
        this.btnActive = true
      },
      endCutdown(item, index) {
        this.$emit('endCutdown', index)
      },

      editOrderInfo: async function(orderNo, flag, isdraw, isspecial, status) {
        let that = this;
        let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt
        let orderInfo = that.orderList[that.listIndex];
        let json;
        if (flag === 3) {
          json = await api.submitOrder({
              method: 'PUT',
              header: {
                jwt: jwt
              },
              query: {}
            },
            orderNo
          );
        } else if (flag === 0) {
          json = await api.cancelOrder({
              method: 'PUT',
              header: {
                jwt: jwt
              },
              query: {}
            },
            orderNo
          );
          if (json.code === 1000) {
            this.btnActive = true
            var timestamp = new Date().getTime();
            that.$sr.track('custom_order', {
              order: {
                order_id: orderInfo.orderCode.toString(),
                order_time: new Date(orderInfo.orderTime.replace(/-/g, "/")).getTime() || new Date(orderInfo
                  .orderTime).getTime(),
                order_status: 'cancel_give_order'
              },
              sub_orders: [{
                sub_order_id: orderInfo.orderCode.toString(),
                order_amt: parseFloat(orderInfo.itemTotal),
                pay_amt: parseFloat(orderInfo.payment)
              }]
              // more...
            });
            // this.$parent.getMyOrder();
            if (!this.openAppointment || !isCancelOrder) {
              this.handleShowTextToast('取消订单成功');
              that.$emit('getMyOrderSale')
            } else {
              this.handleShowTextToast('取消预约成功');
            }
            that.$commonSensors.commonCancelOrder(that.orderList[that.currentCancelIndex])
          }
        }
        if (json.code === 1000) {
          this.$parent.fromSon(flag, status);
        } else {
          that.btnActive = true
        }
      },

      // 获取模板ID
      getTmplIds: async function() {
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
        const tmplIds = await api.customize({
          method: 'POST',
          query: {
            cloudMerchantId: merchantInfo.cloudMerchantId,
            cloudMerchantStoreId: merchantInfo.cloudMerchantStoreId,
            cloudStoreConfigtypeId: 59,
            cloudStoreConfigtypeName: 'Mini_Subscribe_Message_Config'
          }
        });
        if (tmplIds.code == 200 && !!tmplIds.data) {
          const configText = tmplIds.data.cloudStoreConfigText;
          let configTextParse = JSON.parse(configText);
          let orderMessage = [];
          if (configTextParse.paymentMsg == 1) {
            orderMessage.push(configTextParse.paymentTemplateId);
          }
          if (configTextParse.shipmentMsg == 1) {
            orderMessage.push(configTextParse.shipmentTemplateId);
          }
          if (configTextParse.applyRefundMsg == 1) {
            orderMessage.push(configTextParse.applyRefundTemplateId);
          }
          this.subscribeMessage = orderMessage;
        }
      },

      // 查看物流
      checkLogistics: async function(e) {
        this.orderNo = e.currentTarget.dataset.id;
        uni.navigateTo({
          url: '/pages/order/logistics?orderNo=' + this.orderNo
        });
      },
      //订单详情
      orderDetail: async function(item,index) {
        this.orderNo = item.orderId;
        let currentOrder = this.orderList[index];
        let orderFlow = this.$programSetting.openAppointment;
        let obj= this.$commonFunction.isOrderType(currentOrder,orderFlow);
        this.$commonFunction.trackOrder(currentOrder,obj,'c_ebmp_order_view_detail');
        uni.navigateTo({
          url: '/pages/order/details?orderNo=' + this.orderNo
        });
      },

      // 退货退款详情
      goToRmaDetail: async function(e) {
        this.orderNo = e.currentTarget.dataset.id;
        let refundId = e.currentTarget.dataset.refundid;
        uni.navigateTo({
          url: '/pages/return/details?orderNo=' + this.orderNo + '&refundId=' + refundId
        });
      },

      // 确认收货
      completion: async function(e) {
        let that = this;
        let orderCode = e.currentTarget.dataset.ordercode;
        
        if (!orderCode) {
          return false;
        }
        // await tip.confirm('是否确认收货');
				this.$refs.toastPopup.showPopup({
					msg:"是否确认收货",
					callBackData: {
						type: "handleAjaxConfirmOrder",
						data: orderCode
					}})
        
      },
			//	发送确认收货请求
			async handleAjaxConfirmOrder(orderCode){
				let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
				let json = await api.submitOrder({
				    method: 'PUT',
				    header: {
				      jwt: jwt
				    },
				    query: {}
				  },
				  orderCode
				);
				if (json.code === 1000) {
					this.handleShowTextToast('确认收货成功');
				  uni.navigateBack({
				    delta: -1
				  })
				} else {
				  this.handleShowTextToast(json.msg);
				}
			},
      //取消订单
      cancelOrder: async function(e) {
        if ((e.timeStamp - this.touchStartTime) > 1000 && this.btnActive) {
          this.flag = 0;
          this.btnActive = false
          this.orderNo = e.currentTarget.dataset.id;
          this.touchStartTime = e.timeStamp;
          let sale = e.currentTarget.dataset.sale;
          let draw = e.currentTarget.dataset.draw;
          let status = e.currentTarget.dataset.status;
          let isdraw = e.currentTarget.dataset.draw;
          let isspecial = e.currentTarget.dataset.special;
          let index = e.currentTarget.dataset.index;
          this.currentCancelIndex = index
          let currentOrder = this.orderList[index];
          let orderFlow = this.$programSetting.openAppointment;
          let obj= this.$commonFunction.isOrderType(currentOrder,orderFlow);
          this.$commonFunction.trackOrder(currentOrder,obj,'c_ebmp_order_cancel');

          let isCancelOrder = (status === 'WAIT_BUYER_PAY' && !draw && !sale) ? true : false;
					const _obj = {
						orderNo: this.orderNo,
						flag: this.flag,
						isCancelOrder: isCancelOrder
					}
          if (isdraw || isspecial || !this.openAppointment || isCancelOrder) {
            // await tip.confirm('是否取消订单').then(() => {
            //   this.editOrderInfo(this.orderNo, this.flag, isCancelOrder);
            // }).catch(() => {
            //   this.btnActive = true
            // });
						this.$refs.toastPopup.showPopup({
							msg:"是否取消订单",
							callBackData: {
								type: "editOrderInfo",
								data: _obj
							}})
          } else {
            // await tip.confirm('是否取消预约').then(() => {
            //   this.editOrderInfo(this.orderNo, this.flag, isCancelOrder);
            // }).catch(() => {
            //   this.btnActive = true
            // });
						this.$refs.toastPopup.showPopup({
							msg:"是否取消订单",
							callBackData: {
								type: "editOrderInfo",
								data: _obj
							}})
          }
          this.listIndex = e.currentTarget.dataset.index
          // this.editOrderInfo(this.orderNo, this.flag, isdraw, isspecial);
        }
      },

      //付款
      payMoney: async function(e) {
        let that = this;
        if (((e.timeStamp - this.touchStartTime) < 1000) || !this.btnActive) {
          return false
        }
        this.btnActive = false
        const accountInfo = uni.getAccountInfoSync()
        that.getTmplIds();
        let index = e.currentTarget.dataset.index;
        let orderId = e.currentTarget.dataset.id;
        let orderCode = e.currentTarget.dataset.ordercode;
        let payType = e.currentTarget.dataset.paytype;
        //获取item传参埋点
        let currentOrderInfo = this.orderList[index]
        let itemIdArr = []
        let itemArr = []
        currentOrderInfo.items.forEach(function(item, index) {
          itemIdArr.push(item.itemId)
          itemArr.push({
            itemId: item.itemId,
            itemName: item.itemName,
            price: item.price,
            qty: item.qty,
            remark: currentOrderInfo.buyerRemark,
            skuInfo: {
              itemCapacity: item.skuProperties[0].valueName,
            },
          })
        });
        that.$emit('setOrderId', orderId)
        let orderFlow = this.$programSetting.openAppointment;
        let objOrder =  this.$commonFunction.isOrderType(currentOrderInfo,orderFlow);
        that.$commonFunction.payMoney(this.orderList[e.currentTarget.dataset.index],this,objOrder).then((res) => {
          //支付成功 关闭loadding 跳转到支付成功页面
          tip.loaded();
          that.btnActive = true
        }).catch((err) => {
          that.btnActive = true
        })
        this.touchStartTime = e.timeStamp;
      },
      /**
       * 发票页面跳转验证
       * @param {Object} orderId
       */
      async applyInvoice(orderId) {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        const amount = await api.getwosaiInvoiceAmount({
            header: {
              jwt: customerInfo.jwt
            }
          },
          orderId
        );
        if (amount.code === 1000) {
          let invoiceAmount = amount.data.invoiceAmount;
          uni.navigateTo({
            url: '/pages/invoice/apply?orderNo=' + orderId
          });
        }
      },
    }
  };
</script>
<style lang="less">
  .order_item {
    padding: 0 48rpx 150rpx 48rpx;
    over-flow: auto;
    /* winphone8和android4+ */
    -webkit-overflow-scrolling: touch;
    font-family: FrankNew-Regular,NotoSansSC-Regular;

    &.hidePage {
      opacity: 0;
    }
    &.showPage {
      opacity: 1;
    }

    /* ios5+ */
    .title {
      font-size: 26rpx;
      color: #333;
      float: left;
    }

    .order_doc {
      height: 38rpx;
      line-height: 38rpx;
      font-size: 24rpx;
      color: #000;
    }

    .mt10 {
      margin-top: 10rpx;
    }

    .order_state {
      font-family: NotoSansSC-Regular;
      font-size: 20rpx;
      font-weight: normal;
      line-height: 32rpx;
      color: #75777A;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .order_list_top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-left: 32rpx;
      .left {
        display: flex;
      }
    }

    .order_list_footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 16rpx;
      width: 100%;
      .num {
        color: #ff4856;
      }
    }

    .list {
      background: #FAFAFA;
      padding: 32rpx 32rpx 44rpx 0;
      margin-bottom: 24rpx;

      .total {
        text-align: right;
        padding: 10rpx 20rpx 20rpx;
        display: flex;
        position: relative;
        justify-content: flex-end;
        font-size: 28rpx;

        .evaluateText {
          position: absolute;
          left: 20rpx;
          color: #ccc;
        }
      }
    }

    .btn_group {
      display: flex;
      flex-direction: row-reverse;

      .btn {
        border: 2px solid #CB171A;
        margin-left: 24rpx;
        line-height: 56rpx;
        width: 160rpx;
        height: 64rpx;
        border-radius: 32rpx 12rpx 32rpx 32rpx;
        font-family: NotoSansSC-Medium;
        font-size: 24rpx;
        font-weight: 400;
      }

      .btn_del {
        color: #000;
        border: 2px solid #000;
        background-color: transparent;
      }

      .btn_check {
        color: #000;
        border: 2px solid #000;
        background-color: transparent;
      }
    }
  }

  .order_item .order_list_footer {
    display: block;
  }

  .fixed-p {
    color: #adadad;
  }

  .fixed-p2 {
    text-align: right;
  }

  .text {
    font-size: 34rpx;
    line-height: 34rpx;
  }

  .text2 {
    font-size: 28rpx;
    margin-right: 2rpx;
  }
  .order_text{
    font-family: FrankNew-Regular;
    font-size: 20rpx;
    font-weight: normal;
    line-height: 32rpx;
    color: #75777A;
  }
</style>
